<template>
  <div class="user-profile-edit">
    <div class="edit-header">
      <h2>修改个人信息</h2>
      <p>您可以修改以下个人信息，带 * 的字段为必填项</p>
    </div>

    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="edit-form"
    >
      <!-- 头像上传 -->
      <el-form-item label="头像" prop="avatar">
        <div class="avatar-upload">
          <el-avatar
              :size="100"
              :src="resolveAvatarUrl(form.avatar)"
              :icon="!form.avatar ? 'User' : undefined"
          >
            {{ !form.avatar && form.realName ? form.realName.charAt(0) : '' }}
          </el-avatar>
          <div class="upload-actions">
            <el-upload
                ref="uploadRef"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
                accept="image/*"
            >
              <el-button type="primary" size="small">上传头像</el-button>
            </el-upload>
            <el-button
                v-if="form.avatar"
                type="danger"
                size="small"
                @click="removeAvatar"
            >
              删除头像
            </el-button>
          </div>
        </div>
      </el-form-item>

      <!-- 基本信息 -->
      <el-divider content-position="left">基本信息</el-divider>

      <!-- 不可修改的字段 -->
      <el-form-item label="用户名">
        <el-input v-model="form.username" disabled />
        <div class="field-tip">用户名不可修改</div>
      </el-form-item>

      <el-form-item label="身份">
        <el-input v-model="roleDisplayName" disabled />
        <div class="field-tip">身份不可修改</div>
      </el-form-item>

      <el-form-item label="学号/工号">
        <el-input v-model="studentOrTeacherId" disabled />
        <div class="field-tip">学号/工号不可修改</div>
      </el-form-item>

      <!-- 可修改的字段 -->
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="form.realName" placeholder="请输入真实姓名" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择性别">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱地址" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>

      <!-- 学生特有信息 -->
      <template v-if="userInfo.role === 'STUDENT' || userInfo.role === 'student'">
        <el-divider content-position="left">学生信息</el-divider>

        <el-form-item label="院系" prop="department">
          <el-select v-model="form.departmentId" placeholder="请选择院系" @change="handleDepartmentChange">
            <el-option 
              v-for="dept in departments" 
              :key="dept.id" 
              :label="dept.name" 
              :value="dept.id" 
            />
          </el-select>
        </el-form-item>

        <el-form-item label="专业" prop="major">
          <el-select v-model="form.majorId" placeholder="请选择专业" :disabled="!form.departmentId">
            <el-option 
              v-for="major in majors" 
              :key="major.id" 
              :label="major.name" 
              :value="major.id" 
            />
          </el-select>
        </el-form-item>

        <el-form-item label="年级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择年级">
            <el-option label="大一" value="大一" />
            <el-option label="大二" value="大二" />
            <el-option label="大三" value="大三" />
            <el-option label="大四" value="大四" />
            <el-option label="研究生" value="研究生" />
          </el-select>
        </el-form-item>

        <el-form-item label="班级" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级" />
        </el-form-item>
      </template>

      <!-- 教师特有信息 -->
      <template v-if="userInfo.role === 'TEACHER' || userInfo.role === 'teacher'">
        <el-divider content-position="left">教师信息</el-divider>

        <el-form-item label="职称" prop="title">
          <el-select v-model="form.title" placeholder="请选择职称">
            <el-option label="助教" value="助教" />
            <el-option label="讲师" value="讲师" />
            <el-option label="副教授" value="副教授" />
            <el-option label="教授" value="教授" />
          </el-select>
        </el-form-item>

        <el-form-item label="任教科目" prop="subject">
          <el-input v-model="form.subject" placeholder="请输入任教科目" />
        </el-form-item>
      </template>

      <!-- 通用信息 -->
      <el-divider content-position="left">其他信息</el-divider>

      <el-form-item label="身份证号" prop="idNumber">
        <el-input v-model="form.idNumber" placeholder="请输入身份证号" />
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入地址" />
      </el-form-item>

      <el-form-item label="紧急联系人" prop="emergencyContact">
        <el-input v-model="form.emergencyContact" placeholder="请输入紧急联系人" />
      </el-form-item>

      <el-form-item label="紧急联系电话" prop="emergencyPhone">
        <el-input v-model="form.emergencyPhone" placeholder="请输入紧急联系电话" />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          保存修改
        </el-button>
        <el-button @click="handleCancel">取消</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updateUserInfo, uploadAvatar, getUserInfo } from '@/api/user'
import { resolveAvatarUrl } from '@/utils/avatar'
import axios from 'axios'

// 定义props和emits
// eslint-disable-next-line no-undef, no-unused-vars
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

// eslint-disable-next-line no-undef
const emit = defineEmits(['refresh', 'update:visible'])

    const store = useStore()
    const router = useRouter()
    const formRef = ref(null)
    const uploadRef = ref(null)
    const loading = ref(false)
    const departments = ref([])
    const majors = ref([])

const userInfo = computed(() => {
  const user = store.state.user.userInfo || store.state.user
  console.log('UserProfileEdit userInfo computed - store state:', store.state.user)
  console.log('UserProfileEdit userInfo computed - user:', user)
  return user
})

    const roleDisplayName = computed(() => {
      const roleNames = {
        student: '学生',
        teacher: '教师',
        admin: '管理员',
        staff: '后勤人员',
        STUDENT: '学生',
        TEACHER: '教师',
        ADMIN: '管理员',
        STAFF: '后勤人员'
      }
      console.log('userInfo.value', userInfo.value)
      return roleNames[userInfo.value.role] || '未知'
    })

    const studentOrTeacherId = computed(() => {
      return userInfo.value.studentId || userInfo.value.teacherId || ''
    })

    // 表单数据
    const form = reactive({
  id: userInfo.value.id || '',
      username: userInfo.value.username,
      realName: userInfo.value.name || userInfo.value.realName,
      gender: userInfo.value.gender || '',
      email: userInfo.value.email || '',
      phone: userInfo.value.phone || '',
      avatar: userInfo.value.avatar || '',
      role: userInfo.value.role,
      studentId: userInfo.value.studentId || '',
      teacherId: userInfo.value.teacherId || '',
      department: userInfo.value.department || '',
      major: userInfo.value.major || '',
      departmentId: userInfo.value.departmentId || null,
      majorId: userInfo.value.majorId || null,
      grade: userInfo.value.grade || '',
      className: userInfo.value.className || '',
      title: userInfo.value.title || '',
      subject: userInfo.value.subject || '',
      idNumber: userInfo.value.idNumber || '',
      address: userInfo.value.address || '',
      emergencyContact: userInfo.value.emergencyContact || '',
      emergencyPhone: userInfo.value.emergencyPhone || ''
    })

    // 表单验证规则
    const rules = {
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      idNumber: [
        { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
      ]
    }

    // 头像上传前的验证
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('头像只能是 JPG/PNG/GIF 格式!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('头像大小不能超过 2MB!')
        return false
      }
      return true
    }

    // 处理头像上传
    const handleAvatarUpload = async (options) => {
      try {
        loading.value = true
        const formData = new FormData()
        formData.append('file', options.file)

        const response = await uploadAvatar(formData)
        if (response.code === 200) {
          form.avatar = response.data.url
          ElMessage.success('头像上传成功')
          // 上传成功后刷新全局用户信息
          const userInfoResp = await getUserInfo()
          if (userInfoResp.code === 200) {
            store.commit('user/UPDATE_USER_INFO', userInfoResp.data)
          }
        } else {
          ElMessage.error(response.message || '头像上传失败')
        }
      } catch (error) {
        ElMessage.error('头像上传失败')
        console.error('Avatar upload error:', error)
      } finally {
        loading.value = false
      }
    }

    // 删除头像
    const removeAvatar = () => {
      ElMessageBox.confirm('确定要删除头像吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        form.avatar = ''
        ElMessage.success('头像已删除')
      })
    }

    // 获取所有院系
    const fetchDepartments = async () => {
      try {
        const response = await axios.get('/api/departments')
        departments.value = response.data || []
        console.log('获取到院系数量:', departments.value.length)
        
        // 如果用户已有院系ID，获取对应的专业列表
        if (form.departmentId) {
          fetchMajorsByDepartment(form.departmentId)
        }
        // 如果用户有院系名称但没有ID，尝试匹配
        else if (form.department) {
          const dept = departments.value.find(d => d.name === form.department)
          if (dept) {
            form.departmentId = dept.id
            fetchMajorsByDepartment(dept.id)
          }
        }
      } catch (error) {
        console.error('获取院系失败:', error)
        ElMessage.error('获取院系失败')
      }
    }
    
    // 根据院系ID获取专业
    const fetchMajorsByDepartment = async (departmentId) => {
      if (!departmentId) {
        majors.value = []
        return
      }
      
      try {
        const response = await axios.get(`/api/departments/${departmentId}/majors`)
        majors.value = response.data || []
        console.log('获取到专业数量:', majors.value.length)
        
        // 如果用户有专业名称但没有ID，尝试匹配
        if (form.major && !form.majorId) {
          const major = majors.value.find(m => m.name === form.major)
          if (major) {
            form.majorId = major.id
          }
        }
      } catch (error) {
        console.error('获取专业失败:', error)
        ElMessage.error('获取专业失败')
      }
    }
    
    // 处理院系变更
    const handleDepartmentChange = (departmentId) => {
      form.majorId = null
      form.major = '' // 清空专业名称
      fetchMajorsByDepartment(departmentId)
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (!valid) {
          ElMessage.error('请正确填写表单')
          return
        }
        
        loading.value = true
        
        try {
          // 如果是学生，根据选择的院系和专业ID设置对应的名称
          if ((form.role === 'STUDENT' || form.role === 'student') && form.departmentId && form.majorId) {
            // 查找院系名称
            const dept = departments.value.find(d => d.id === form.departmentId)
            if (dept) {
              form.department = dept.name
            }
            
            // 查找专业名称
            const major = majors.value.find(m => m.id === form.majorId)
            if (major) {
              form.major = major.name
            }
          }
          
          // 确保ID作为字符串处理
          const updateData = {
            ...form,
            id: String(form.id) // 强制转换为字符串
          }

          console.log('Submitting update data:', updateData)
          
          await updateUserInfo(updateData)
          
          ElMessage.success('用户信息更新成功')
          
          // 刷新用户信息
          await store.dispatch('user/refreshUserInfo')
          
          // 关闭对话框
          emit('update:visible', false)
          
          // 触发父组件刷新
          emit('refresh')
          
        } catch (error) {
          console.error('Update error:', error)
          ElMessage.error(error.response?.data?.message || '更新失败')
        } finally {
          loading.value = false
        }
      })
    }

    const handleCancel = () => {
      router.back()
    }

    const handleReset = () => {
      ElMessageBox.confirm('确定要重置表单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        formRef.value.resetFields()
        // 重新加载用户信息
        Object.assign(form, {
      id: userInfo.value.id || '',
          username: userInfo.value.username,
          realName: userInfo.value.name || userInfo.value.realName,
          gender: userInfo.value.gender || '',
          email: userInfo.value.email || '',
          phone: userInfo.value.phone || '',
          avatar: userInfo.value.avatar || '',
          role: userInfo.value.role,
          studentId: userInfo.value.studentId || '',
          teacherId: userInfo.value.teacherId || '',
          department: userInfo.value.department || '',
          major: userInfo.value.major || '',
          departmentId: userInfo.value.departmentId || null,
          majorId: userInfo.value.majorId || null,
          grade: userInfo.value.grade || '',
          className: userInfo.value.className || '',
          title: userInfo.value.title || '',
          subject: userInfo.value.subject || '',
          idNumber: userInfo.value.idNumber || '',
          address: userInfo.value.address || '',
          emergencyContact: userInfo.value.emergencyContact || '',
          emergencyPhone: userInfo.value.emergencyPhone || ''
        })
        ElMessage.success('表单已重置')
      })
    }

    onMounted(() => {
      // 获取最新的用户信息
      getUserInfo().then(response => {
        const userData = response.data
        if (userData) {
          Object.keys(form).forEach(key => {
            if (key in userData) {
              form[key] = userData[key]
            }
          })
        }
        
        // 获取院系和专业数据
        fetchDepartments()
      })
    })

</script>

<style scoped>
.user-profile-edit {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.edit-header {
  text-align: center;
  margin-bottom: 30px;
}

.edit-header h2 {
  color: var(--text-color);
  margin-bottom: 8px;
}

.edit-header p {
  color: var(--text-color-secondary);
  font-size: 14px;
}

.edit-form {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 20px;
}

.upload-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.field-tip {
  font-size: 12px;
  color: var(--text-color-secondary);
  margin-top: 4px;
}

.el-divider {
  margin: 30px 0 20px;
}

.el-divider__text {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

@media (max-width: 768px) {
  .user-profile-edit {
    padding: 10px;
  }

  .edit-form {
    padding: 20px;
  }

  .avatar-upload {
    flex-direction: column;
    align-items: center;
  }
}
</style>